//
//  CApplication.m
//  chameleon
//
//  Created by Justin Yip on 6/16/14.
//
//

#import "CApplication.h"
#import "NSFileManager+Chameleon.h"
#import "SSZipArchive.h"
#import <ReactiveCocoa.h>
#import "NSDataEncrypt.h"
#import "EncryptedFileURLProtocol.h"


static NSString *kInstalledVersionKey = @"InsatalldVersion";
static NSString *kInstalled = @"Installed";

NSString* const kAppResetNotification = @"kAppResetNotification";
NSString* const kWWWFolderName = @"app";

@implementation CApplication

+ (instancetype)sharedApplication
{
    static CApplication *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[CApplication alloc] init];
    });
    
    return instance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reset) name:kAppResetNotification object:nil];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveResetNotification:(NSNotification*)note
{
    [self reset];
}

/**
 * 将应用包里的预装目录复制到Documents里
 * TODO：预装模块如果版本大于现有版本，提示后覆盖更新
 */
-(void)launch
{
    NSString *currentBuild = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *installedVersion = [ud objectForKey:kInstalledVersionKey];
    if ([currentBuild compare:installedVersion] == NSOrderedDescending) {
        NSLog(@"Install Web App, Current Version: %@, Installed Version: %@", currentBuild, installedVersion);
        
        [self installWebApp];

        [ud setObject:currentBuild forKey:kInstalledVersionKey];
        [ud synchronize];
    } else {
        NSLog(@"Current Version: %@ is already Install", currentBuild);
    }
}

- (void)installWebApp
{
    NSError *error = nil;
    NSFileManager *fs = [NSFileManager defaultManager];
    
    //应用内app目录
    NSURL *bundledAppURL = [NSFileManager bundledAppDirectory];
    //Documents/app目录(H5沙箱运行时)
    NSURL *runtimeWWWURL = [NSFileManager webRuntimeDirectory];
    //加密的密码
    NSString *AESPassword = [EncryptedFileURLProtocol key];
    
    if (![fs fileExistsAtPath:bundledAppURL.path]) {
        NSLog(@"app folder in package not exists, Nothing to Install");
        return;
    }
    
    //复制安装包内，较新的模块
    NSArray *subDirsInBundledApp = [fs contentsOfDirectoryAtPath:bundledAppURL.path error:&error];
    
    NSArray *pendingModules = [[subDirsInBundledApp.rac_sequence filter:^BOOL(NSString *path) {
        
        path = [[bundledAppURL URLByAppendingPathComponent:path] URLByAppendingPathComponent:@"package.json"].path;
        return [fs fileExistsAtPath:path];
    }] filter:^BOOL(NSString *module) {
        
        NSURL *src = [[bundledAppURL URLByAppendingPathComponent:module isDirectory:YES] URLByAppendingPathComponent:@"package.json"];
        NSURL *dest = [[runtimeWWWURL URLByAppendingPathComponent:module isDirectory:YES] URLByAppendingPathComponent:@"package.json"];
        
        
        if ([fs fileExistsAtPath:dest.path]) {
            
            id src_package = [NSJSONSerialization JSONObjectWithData:[NSData aesDecryptFile:src key:[AESPassword md5Data]] options:0 error:nil];
            id dest_package = [NSJSONSerialization JSONObjectWithData:[NSData aesDecryptFile:dest key:[AESPassword md5Data]] options:0 error:nil];
            
            NSString *src_version = src_package[@"version"];
            NSString *dest_version =dest_package[@"version"];
            
            return [src_version compare:dest_version] == NSOrderedDescending;
            
        } else {
            
            return YES;
        }
    }].array;
    
    //加上cordova三个文件，作为特例
    NSMutableArray *mutablePendingModules = [NSMutableArray arrayWithArray:pendingModules];
    [mutablePendingModules addObject:@"cordova.js"];
    [mutablePendingModules addObject:@"cordova_plugins.js"];
    [mutablePendingModules addObject:@"plugins"];
    
    //创建runtime目录
    [fs createDirectoryAtURL:runtimeWWWURL withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSLog(@"Modules to be Installed: [%@]", [mutablePendingModules componentsJoinedByString:@","]);
    [mutablePendingModules enumerateObjectsUsingBlock:^(NSString *module, NSUInteger idx, BOOL *stop) {
        
        NSURL *src = [bundledAppURL URLByAppendingPathComponent:module];
        NSURL *dest = [runtimeWWWURL URLByAppendingPathComponent:module];
        
        NSError *err;
        BOOL result;
        result = [fs removeItemAtURL:dest error:&err];
        result = [fs copyItemAtURL:src toURL:dest error:&err];
    }];

}

- (void)reset
{
    NSLog(@"Reset Application");
    NSFileManager *fs = [NSFileManager defaultManager];
    
    NSString *installedFlagFilePath = [[[NSFileManager documentsDirectory] URLByAppendingPathComponent:@"Installed"] path];
    [fs removeItemAtPath:installedFlagFilePath error:nil];
    
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"修复完成" message:@"请重新启动应用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [av show];
}

@end
